//
//  SFCAppDelegate.m
//  SVNForCocoa
//
//  Created by Jeremy Pereira on 06/12/2013.
//  Copyright (c) 2013 Jeremy Pereira. All rights reserved.
//

#import "SFCAppDelegate.h"
#import "SFCDocumentController.h"
#import "SFCError.h"
#import "SFCPreferenceViewController.h"

@interface SFCAppDelegate()
/*!
 *    @brief Gets the working copy root of the given resource which should be
 *           a file URL.
 *
 *    This works by ascendig the directory hierarchy until a directory is found
 *    containing a .svn subdirectory.
 *
 *    @param fileResource The URL of an oject in the file system.
 *    @return The working copy root of the given resource or nil if the resource
 *            isn't in a working copy.
 */
+(NSURL*) workingCopyRoot: (NSURL*) fileResource;

@end

@implementation SFCAppDelegate
{
    SFCPreferenceViewController* preferencesController;
}

@synthesize documentController = _documentController;

-(void) applicationDidFinishLaunching:(NSNotification*) notification
{
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary* defaultDefaults = @{SFC_PREFS_DEBUG_CONSTRAINTS : @(NO)};
    [defaults registerDefaults: defaultDefaults];
}
/*
 *  Currently can only opern existing working copies.
 */
-(BOOL) applicationShouldOpenUntitledFile:(NSApplication *)sender
{
    return NO;
}

-(IBAction) openSvnDir: (id) sender
{
    NSOpenPanel* openPanel = [NSOpenPanel openPanel];
    [openPanel setCanChooseFiles: NO];
    [openPanel setCanChooseDirectories: YES];
    [openPanel setCanCreateDirectories: NO];
    [openPanel setAllowsMultipleSelection: NO];
    [openPanel setDelegate: self];
    [openPanel beginWithCompletionHandler:
        ^(NSInteger result)
        {
            if (result == NSFileHandlingPanelOKButton)
            {
                NSURL* theUrl = [[self class] workingCopyRoot: [[openPanel URLs] objectAtIndex: 0]];
                [[self documentController] openDocumentWithContentsOfURL: theUrl
                                                                 display: YES
                                                       completionHandler:
                 ^(NSDocument *document, BOOL documentWasAlreadyOpen, NSError *error)
                 {
                     // TODO: present the error if any
                 }];
            }
        }];
}

-(BOOL) panel: (id) sender
  validateURL: (NSURL*) url
        error: (NSError* __autoreleasing*) outError
{
    NSLog(@"validating %@", url);

    BOOL isInWorkingCopy = [[self class] workingCopyRoot: url] != nil;
    if (!isInWorkingCopy && outError != nil)
    {
		NSDictionary* errorInfo
        	= @{ NSLocalizedDescriptionKey: NSLocalizedString(@"The selected directory is not in a working copy", @"")};
        *outError = [NSError errorWithDomain: SFC_ERROR_DOMAIN
                                        code: SFC_ERROR_NOT_A_WORKING_COPY
                                    userInfo: errorInfo];
    }
    return isInWorkingCopy;
}

+(NSURL*) workingCopyRoot: (NSURL*) fileResource
{
    bool rootFound = false;
    NSString* path = [fileResource path];
    NSFileManager* fm = [NSFileManager defaultManager];

    while (!rootFound && [path length] > 1)
    {
        BOOL isDirectory;
        if ([fm fileExistsAtPath: path isDirectory: &isDirectory] && isDirectory)
        {
            NSString* svnDir = [path stringByAppendingPathComponent: @".svn"];
            rootFound = [fm fileExistsAtPath: svnDir isDirectory: &isDirectory] && isDirectory;
            if (!rootFound)
            {
                path = [path stringByDeletingLastPathComponent];
            }
        }
    }
	return rootFound ? [NSURL fileURLWithPath: path] : nil;
}

-(IBAction) showPreferences: (id) sender
{
    if (preferencesController == nil)
    {
        preferencesController
            = [[SFCPreferenceViewController alloc] initWithWindowNibName: @"Preferences"];
    }
    [preferencesController showWindow: self];
}


@end
